package com.biz.primus.ms.order.promotion;

import com.biz.primus.base.enums.PromotionTypeEnum;
import com.biz.primus.model.order.vo.request.OrderItemRequestVO;
import com.biz.primus.model.order.vo.request.OrderRequestVO;
import com.biz.primus.model.promotion.vo.DiscountProductVo;
import com.biz.primus.model.promotion.vo.OrderPromotionDetailVo;
import com.biz.primus.ms.order.promotion.helper.OrderPromotionHelper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 折扣促销
 * <p>ISCOUNT("折扣促销", "折"),</p>
 *
 * @author Tiger Feng
 * @date 2017年11月09日
 */
public class DiscountPromotionHandler extends AbstractPromotionHandler {
    /**
     * 禁止无参构造
     */
    private DiscountPromotionHandler() {
    }

    public DiscountPromotionHandler(
            OrderPromotionDetailVo orderPromotionDetailVo,
            OrderRequestVO orderRequestVO,
            OrderPromotionHelper orderPromotionHelper) {
        super(orderPromotionDetailVo, orderRequestVO, orderPromotionHelper);
    }

    @Override
    public boolean checkPromotionType() {
        return orderPromotionDetailVo.getPromotionType() == PromotionTypeEnum.DISCOUNT;
    }

    @Override
    public void count() {
        // 折扣促销商品信息为空
        if (orderPromotionDetailVo.getDiscountProducts() == null || orderPromotionDetailVo.getDiscountProducts().isEmpty()) {
            return;
        }
        Map<Long, DiscountProductVo> discountProductVoMap = discountProductList2Map(orderPromotionDetailVo.getDiscountProducts());
        for (OrderItemRequestVO itemRequestVO : orderRequestVO.getItems()) {
            DiscountProductVo discountProductVo = discountProductVoMap.get(itemRequestVO.getProductId());
            if (discountProductVo == null) {
                continue;
            }
            // 设置当前商品优惠金额
            itemRequestVO.setDiscountPromotionMoney(
                    discountProductVo.getOriginalProductAmount() - discountProductVo.getDiscountProductAmount());
            // 设置商品最终价
            itemRequestVO.setFinalPrice(discountProductVo.getDiscountProductAmount());
            // 设置商品价格
            itemRequestVO.setFclSinglePrice(discountProductVo.getOriginalProductAmount());
        }
    }

    /**
     * 折扣促销商品列表转Map
     *
     * @param discountProducts
     * @return
     */
    private Map<Long, DiscountProductVo> discountProductList2Map(List<DiscountProductVo> discountProducts) {
        return discountProducts.stream().collect(Collectors.toMap(d -> d.getProductId(), d -> d));
    }


}
